#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/08/08 13:17:47
'''

import sys


sys.path.append('.')

from sqlalchemy import and_
from Common.Utils import Utils
from db_logic.db_base import Repository
from models.user_models import EntityUserMedicament


class BllUserMedicament(Repository):

    def __init__(self, entityType=EntityUserMedicament):
        super().__init__(entityType)
    
    def is_jin_zhi_user(self, user_id, drug_id):
        obj = self.findEntity(and_(
            EntityUserMedicament.user_id==user_id,
            EntityUserMedicament.drug_id==drug_id
        ))
        # 无记录返回True
        # 有记录返回Flase
        if obj:
            return False
        else:
            return True
    
    def get_user_jin_medicament(self, seach_user, drug_id, page_param):
        filter_base = ""
        if seach_user:
            filter_base += f" real_name like '%{seach_user}%'"
        if filter_base:
            filter_base =  f" where {filter_base}"

        sql_all = f"""
        select 
        a.user_id, a.real_name, a.role_name, 
        CASE WHEN b.id is not null THEN 1 else 0 END status_type
        from (select * from rms_user {filter_base}) as a 
        LEFT JOIN (select id, user_id, drug_id from rms_user_medicament WHERE drug_id='{drug_id}')
        as b on a.user_id=b.user_id
        """
        try:
            count_number = len(self.execute(sql_all).fetchall())
        except Exception:
            count_number = 0
        page_param.totalRecords= count_number
        page_sql = Utils.sql_paging_assemble(sql_all,page_param)
        return self.execute(page_sql).fetchall()
    
    def get_user_drug_name(self, user_id):
        sql_all = f"""
        SELECT b.variety_id, b.`name` from (
	        select * from rms_user_medicament where user_id= '{user_id}'
        ) a LEFT JOIN rms_medicament_variety as b on a.drug_id=b.variety_id
        """
        return self.execute(sql_all).fetchall()
    
    def del_user_ban_drug(self, user_id, drug_id):
        try:
            self.delete(and_(
                EntityUserMedicament.user_id == user_id,
                EntityUserMedicament.drug_id == drug_id
            ))
            # data_list = self.findList(and_(
            #     EntityUserMedicament.user_id==user_id,
            #     EntityUserMedicament.drug_id.in_(eval(drug_list))
            # )).all()
            # for i in data_list:
            #     self.session.delete(i)
            # self.session.commit()
            return True
        except:
            return False


    def inster_user_drug(self, user_id, variety_id):
        try:
            obj = EntityUserMedicament(
                user_id=user_id,
                drug_id=variety_id
            )
            self.insert(obj)
            return True
        except:
            return False